package 数组算法;

/**
 * @Classname rob198
 * @Description TODO
 * @Date 2022/3/7 22:34
 * @Created by xjl
 */
public class rob198 {
    /**
     * @description 坐标转移的方程是：dp[i]=Math.max(dp[i-2]+nums[i],dp[i-1])
     * dp[0]=nums[0]
     * dp[1]=Math.max(nums[0],nums[1])
     * 这里的时间和空空间复杂度为o(n)
     * @param: nums
     * @date: 2022/3/7 22:40
     * @return: int
     * @author: xjl
     */
    public int rob(int[] nums) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        int length = nums.length;
        if (length == 1) {
            return nums[0];
        }
        int[] dp = new int[length];
        dp[0] = nums[0];
        dp[1] = Math.max(nums[0], nums[1]);
        for (int i = 2; i < length; i++) {
            dp[i] = Math.max(dp[i - 2] + nums[i], dp[i - 1]);
        }
        return dp[length - 1];
    }

    /**
     * @description 采用空间复杂度为o(1)
     * @param: nums
     * @date: 2022/3/7 22:46
     * @return: int
     * @author: xjl
     */
    public int robV2(int[] nums) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        int length = nums.length;
        if (length == 1) {
            return nums[0];
        }
        int first = nums[0], second = Math.max(nums[0], nums[1]);
        for (int i = 2; i < length; i++) {
            int tmp = second;
            second = Math.max(first + nums[i], second);
            first = tmp;
        }
        return second;
    }
}